package com.lamb.script.core.executor.loader;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;

/**
 * 脚本内url处理器.
 *
 * @author lamb
 */
class ScriptUrlStreamHandler extends URLStreamHandler {

    private final ScriptClassLoader classLoader;

    ScriptUrlStreamHandler(ScriptClassLoader classLoader) {
        this.classLoader = classLoader;
    }

    @Override
    protected URLConnection openConnection(URL u) {
        byte[] bytes = classLoader.getContentByUrl(u);
        return new URLConnection(u) {
            @Override
            public void connect() {
            }

            @Override
            public int getContentLength() {
                return bytes.length;
            }

            @Override
            public InputStream getInputStream() {
                return new ByteArrayInputStream(bytes);
            }
        };
    }

}
